package com.alander.nexusgo.post.controller;

import com.alander.nexusgo.common.model.dto.PostCommentsListDTO;
import com.alander.nexusgo.common.model.vo.PostCommentsVO;
import com.alander.nexusgo.common.response.Result;
import com.alander.nexusgo.framework.web.starter.controller.BaseController;
import com.alander.nexusgo.post.model.entity.PostComments;
import com.alander.nexusgo.post.service.PostCommentsService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.alander.nexusgo.framework.mysql.starter.page.PageUtils.getPageInfo;
import static com.alander.nexusgo.framework.mysql.starter.page.PageUtils.startPage;

/**
* 评论管理
*/
@RestController
@RequestMapping("/api/comments")
public class PostCommentsController extends BaseController {
    
    @Autowired
    private PostCommentsService postCommentsService;
    
    /**
     * 添加评论
     */
    @PostMapping
    public Result<PostCommentsVO> create(@RequestBody PostComments comment) {
        try {
            PostCommentsVO result = postCommentsService.createComment(comment, getUserId());
            return success(result);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }
    
    /**
     * 获取评论详情
     */
    @GetMapping("/{id}")
    public Result<PostCommentsVO> get(@PathVariable(value = "id") Long id) {
        PostCommentsVO comment = postCommentsService.getCommentById(id);
        if (comment == null) {
            return fail("评论不存在");
        }
        return success(comment);
    }
    
    /**
     * 更新评论
     */
    @PutMapping("/{id}")
    public Result<PostCommentsVO> update(@PathVariable(value = "id") Long id, @RequestBody PostComments comment) {
        try {
            PostCommentsVO result = postCommentsService.updateComment(id, comment, getUserId());
            return success(result);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }
    
    /**
     * 删除评论
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable(value = "id") Long id) {
        try {
            boolean result = postCommentsService.deleteComment(id, getUserId());
            if (result) {
                return success();
            } else {
                return fail("删除失败");
            }
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }
    
    /**
     * 分页查询评论列表
     */
    @GetMapping
    public PageInfo<PostCommentsVO> list(@RequestBody PostCommentsListDTO postCommentsListDTO) {
        startPage(postCommentsListDTO);
        List<PostCommentsVO> commentsVOList = postCommentsService.listComments(postCommentsListDTO);
        return getPageInfo(commentsVOList);
    }
}